package com.google.googlemarket.base;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.googlemarket.R;
import com.google.googlemarket.view.LoadMoreListView;
import com.google.googlemarket.view.Statelayout;

import java.util.ArrayList;

/**
 * Created by Administrator on 2017/9/18.
 */

public abstract class BaseFragment extends Fragment {

    public Activity mContext;
    public Statelayout mStateLayout;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mContext = getActivity();
        mStateLayout = new Statelayout(mContext);
        View contentView = getContentView();

        if (contentView!=null){
            mStateLayout.setContentView(contentView);
        }else {
            mStateLayout.setContentView(getContentViewLayoutId());
        }
        initView();
        initListener();
        initData();
        return mStateLayout;
    }

    public <T> T findView(int id){
        @SuppressWarnings("unchecked")
        T view = (T)mStateLayout.findViewById(id);
        return view;
    }


    public void requestAsyncTask(final int type) {
        new AsyncTask<Void,Void,Object>(){

            @Override
            protected Object doInBackground(Void... params) {
                return BaseFragment.this.doInBackground(type);
            }

            @Override
            protected void onPostExecute(Object result) {
                BaseFragment.this.onPostExecute(type,result);
            }
        }.execute();
    }


    public boolean checkInitData(ArrayList datas) {
        boolean result = false;
        if (datas==null){
            mStateLayout.showFailView();
        }else if (datas.isEmpty()){
            mStateLayout.showEmptyView();
        }else{
            mStateLayout.showContentView();
            result=true;
        }
        return result;
    }

    public boolean checkLoadMoreData(ArrayList datas, LoadMoreListView mListView){
        boolean result=false;
        if (datas==null){
            mListView.showRetry();
        }else if(datas.isEmpty()){
            mListView.showLoadingMore();
        }else{
            result=true;
        }
        return result;
    }

    public abstract CharSequence getTitle();

    public abstract void initView();

    public abstract void initListener();

    public abstract void initData();

    public abstract int getContentViewLayoutId();

    public abstract View getContentView();

    protected abstract Object doInBackground(int type);

    protected abstract void onPostExecute(int requestType,Object result);
}
